#!/usr/bin/env python

import os

from PyQt4 import uic


DEFAULT_DIRECTORY = os.path.join(
    os.path.dirname(os.path.realpath(__file__)),
    'UI'
    )

FNAMES_TO_DIRS = {}
DIRS_TO_DIRS = {
    os.path.join('UI','dialogs') : os.path.join('src','limber','ui','dialogs'),
    }


def fname_mapper(dir, fname):
    '''Return a tuple of (directory, filename) where the compiled
    file will be saved.
    '''
    
    base = os.path.basename(fname)
    try:
        new_dir = FNAMES_TO_DIRS[base]
    except KeyError:
        try:
            new_dir = DIRS_TO_DIRS[path_from_repo(dir)]
        except KeyError:
            new_dir = dir
    
    new_fname = 'ui_%s' % base
    return (new_dir, new_fname)


def path_from_repo(path):
    '''Return the path relative to the repository.'''
    
    path = os.path.realpath(path)
    try:
        index = path.index('limbereditor')
        return path[index + len('limbereditor') + 1:]
    except ValueError:
        return path


def compile(directory=DEFAULT_DIRECTORY, mapper=fname_mapper, **kwargs):
    '''Compiles all the files contained in *directory*.'''
    
    uic.compileUiDir(directory, True, mapper, **kwargs)



if __name__ == '__main__':
    import sys
    
    if len(sys.argv) >= 2:
        dirs = sys.argv[1:]
    else:
        dirs = [DEFAULT_DIRECTORY]
    
    for dir in dirs:
        compile(dir)